package io.wongxd.solution.compose.custom.views.chain_scrollable_component

import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import io.wongxd.solution.compose.custom.views.util.midOf

/**
 * effect : 对应[ChainMode.ContentFirst]的[NestedScrollConnection]
 */
internal class ContentFirstNestedScrollConnection(
    val state: ChainScrollableComponentState,
) : NestedScrollConnection {

    override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
        // TODO 2022/9/30 处理抬起事件,处理 ContentFirst缺少数据应对向上滑动收起
        if (true)
            throw RuntimeException("该模式待完善,请使用[ChainMode.ChainContentFirst]")
        val delta = if (state.orientationIsHorizontal) available.x else available.y
        if (delta < 0) {
            val newOffset = state.getScrollPositionValue() + delta
            //Log.e("lllttt", "pre \t $delta\t ${state.minPx}\t ${state.maxPx}\t $newOffset")
            state.setScrollPosition(midOf(state.minPx, newOffset, state.maxPx))
        } else {
            val newOffset = state.getScrollPositionValue() + delta
            //Log.e("lllttt", "pre2 \t $delta\t ${state.minPx}\t ${state.maxPx}\t $newOffset")
            if (newOffset >= state.maxPx)
                state.setScrollPosition(midOf(state.minPx, newOffset, state.maxPx))
        }
        return Offset.Zero
    }
}